/**
 * ajax
 * @param {url} url 
 * @param {请求参数} options 
 */
function ajax(url, options, callback){
    var method              = options.method || "GET",
        responseType        = options.responseType || "text",
        data                = options.data || null;

    var xhr = createXHR();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if((xhr.status >= 200 && xhr.status <300) || xhr.status == 304){
                callback.call(null,xhr.responseText);
            }else{
                throw new Error("ajax未获取到数据!");
            }
        }
    }
    xhr.responseType = responseType;
    xhr.open(method, url, true);
    xhr.send(data);
}



function createXHR(){
    if(typeof XMLHttpRequest !== "undefined"){
        return new XMLHttpRequest();
    }else if(typeof ActiveXObject != "undefined"){
        var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHTTP"];
        var i, len, version = null;
        for(var i=0,len=versions.length;i<len;i++){
            try{
                new ActiveXObject(versions[i]);
                version = versions[i];
                break
            }catch(ex){ }
        }
        
        return new ActiveXObject(versions[i]);
    }else{
        throw new Error("XHR对象创建失败!")
    }
}
export { ajax };